package com.gxy.learn.securityauth.auth;

import com.gxy.learn.securityauth.auth.filter.LoginAuthenticationFilter;
import com.gxy.learn.securityauth.auth.filter.MyLogoutSuccessHandler;
import com.gxy.learn.securityauth.auth.filter.SecurityAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Description(Security配置)
 * @author: Gao xueyong
 * Create at: 2021/12/1 下午10:26
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${spring.security.loginurl:/login}")
    private String loginurl;

    @Autowired
    private SecurityAccessDeniedHandler securityAccessDeniedHandler;

    @Autowired
    private MyLogoutSuccessHandler myLogoutSuccessHandler;

    @Autowired
    private SecurityAuthenticationTokenFilter securityAuthenticationTokenFilter;
    @Autowired
    private MyAccessDecisionManager myAccessDecisionManager;
    @Autowired
    private MySecurityMetadataSource mySecurityMetadataSource;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    protected LoginAuthenticationFilter loginAuthenticationFilter() {
        return new LoginAuthenticationFilter(loginurl);
    }


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .logout().logoutUrl("/logout").logoutSuccessHandler(myLogoutSuccessHandler).clearAuthentication(true)
                .and()
                .authorizeRequests()
                .antMatchers(loginurl).permitAll()
                .anyRequest().authenticated().withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(myAccessDecisionManager);//注入用户登录权限
                        object.setSecurityMetadataSource(mySecurityMetadataSource);//注入用户所请求的地址所需要的权限
                        return object;
                    }
                })
                .and()
                .addFilterAt(loginAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilterAfter(securityAuthenticationTokenFilter, LoginAuthenticationFilter.class)
                .exceptionHandling()
                // 自定义权限不足处理类
                .accessDeniedHandler(securityAccessDeniedHandler)
                .and()
                //设置无状态的连接,即不创建session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().cors().and().csrf().disable();
        // disable page caching
        httpSecurity.headers().cacheControl();
    }

}